<?php

namespace app\admin\controller\inventory;

use app\common\controller\Backend;
use think\Db;
use think\Exception;

/**
 * 库存管理管理
 *
 * @icon fa fa-circle-o
 */
class Kc extends Backend
{

    /**
     * Kc模型对象
     * @var \app\admin\model\inventory\Kc
     */
    protected $model = null;
    protected $vmodel = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\inventory\Kc;
        $this->vmodel = new \app\admin\model\inventory\Kcview;
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->vmodel
        ->where($where)
        ->order($sort, $order)
        ->paginate($limit);
        $listArray = $list->items();
        $inventory=[];
        foreach ($listArray as $k => $v) {
            $inventory[] = $v['cInvCode'];
        }
        $inventoryList = Db::name('inventory')->where('number','in',$inventory)->field('number,name,specification,unit')->select();
        $inventoryList = $this->makeData($inventoryList,'number');
        
        foreach ($listArray as $kk=>&$vv){
            $vv['name']          = '';
            $vv['specification'] = '';
            $vv['unit']          = '';
            if(isset($inventoryList[$vv['cInvCode']])){
                $inventoryInfo       = $inventoryList[$vv['cInvCode']];
                $vv['name']          = $inventoryInfo['name'];
                $vv['specification'] = $inventoryInfo['specification'];
                $vv['unit']          = $inventoryInfo['unit'];
            }
        }
        
        $result = ['total' => $list->total(), 'rows' => $listArray];
        return json($result);
    }
    
    //选择器界面

    public function index2()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        $condition = " kc.cInvCode=inventory.number and inventory.attributes=kc.cFree1 and inventory.deletetime is null";
        $houseCondition = " kc.cWhCode=warehouse.number and warehouse.deletetime is null";  //仓库
        $shelvesCondition = " kc.shelves_id=shelves.id  and shelves.deletetime is null";//货架
        //inventory.name,inventory.specification,inventory.unit,inventory.id as aid
        //->field('kc.*,inventory.name,inventory.specification,inventory.unit,inventory.id as aid,warehouse.name as whname,shelves.name as shname')
        
        //setParam(['shelves.name'=>'shname']);
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $listArray = $list->items();
        $inventory=[];
        $warehouse=[];
        $shelves = [];
        foreach ($listArray as $k => $v) {
            $inventory[] = $v['cInvCode'];
            $warehouse[] = $v['cWhCode'];
            $shelves[]   = $v['shelves_id'];
        }
        $inventoryList = Db::name('inventory')->where('number','in',$inventory)->field('number,name,specification,unit')->select();
        $warehouseList = Db::name('warehouse')->where('number','in',$warehouse)->field('name,number')->select();
        $shelvesList   = Db::name('shelves')->where('id','in',$shelves)->field('id,name')->select();

        $inventoryList = $this->makeData($inventoryList,'number');
        $warehouseList = $this->makeData($warehouseList,'number');
        $shelvesList = $this->makeData($shelvesList,'id');
        //inventory.name,inventory.specification,inventory.unit,inventory.id as aid

        foreach ($listArray as $kk=>&$vv){
            $vv['name']          = '';
            $vv['specification'] = '';
            $vv['unit']          = '';
            $vv['whname']        = '';
            $vv['shname']        = '';

            if(isset($inventoryList[$vv['cInvCode']])){
                $inventoryInfo       = $inventoryList[$vv['cInvCode']];
                $vv['name']          = $inventoryInfo['name'];
                $vv['specification'] = $inventoryInfo['specification'];
                $vv['unit']          = $inventoryInfo['unit'];
            }
            if(isset($warehouseList[$vv['cWhCode']])){
                $warehouseInfo        = $warehouseList[$vv['cWhCode']];
                $vv['whname']         = $warehouseInfo['name'];
            }
            if(isset($shelvesList[$vv['shelves_id']])){
                $shelvesInfo          = $shelvesList[$vv['shelves_id']];
                $vv['shname']         = $shelvesInfo['name'];
            }

        }
        $result = ['total' => $list->total(), 'rows' => $listArray];
        return json($result);
    }
    public function makeData($data,$key){
        if(empty($data)){
            return $data;
        }
        $returnData = [];
        foreach ($data as $k=>$v){
            $returnData[$v[$key]] = $v;
        }
        return $returnData;
    }


    /**
     * 同步数据
     */
    public function getData()
    {
        Db::startTrans();
        try {
            $count =$this->getSql()->count();
            $newList =[];
            if($count>1000) {
                for($i=1;$i<=(intval($count/1000)+1);$i++){
                    $data = $this->getSql()->page($i,1000)->select();
                    $newList = array_merge($newList,$data);
                }
            }else{
                $newList = $this->getSql()->select();
            }
            foreach ($newList as $value) {
                $data = [
                    'AutoID' => $value['AutoID'],
                    'warehouse_id'=>Db::name('warehouse')->where(['number'=>$value['cWhCode']])->value('id'),
                    'cWhCode' => $value['cWhCode'],
                    'cInvCode' => $value['cInvCode'],
                    'cBatch' => $value['cBatch'],
                    'iQuantity'=>$value['iQuantity'],
                    'cFree1' => $value['cFree1'],
                    'dMdate' => $value['dMdate'],
                    'dVDate' => $value['dVDate'],
                    'iMassDate' => $value['iMassDate'],
                    'dLastCheckDate' => $value['dLastCheckDate'],
                    'createtime'=>date('Y-m-d H:i:s',time())
                ];
                if (!Db::name('kc')->where([ 'AutoID' => $value['AutoID'],'deletetime'=>null])->find()){
                     Db::name('kc')->insert($data);
                }
            }
            Db::commit();
            $this->success("同步完成");
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }

    }

    /**
     * 构建查询
     * @return \think\db\Query
     * @throws \think\Exception
     */

    public function getSql()
    {
        $sql = Db::connect('database.sec')->table('CurrentStock')
            ->where([
                'iQuantity' => ['GT',0]
            ])
            ->field('AutoID,cWhCode,cInvCode,cInvCode,cBatch,iQuantity,cFree1,dMdate,dVDate,iMassDate,dLastCheckDate,cCheckState');
        return $sql;
    }
    public function edit($ids = null){

        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if (empty($params)) {
                $this->error(__('Parameter %s can not be empty', ''));
            }

            $result = $row->save($params);
            if (false === $result) {
                $this->error(__('No rows were updated'));
            }
            $this->success();
        }
        //默认没有货架，调用物料的货架
        if (empty($row['shelves_id'])) {
            $inventoryInfo          = Db::name('inventory')->where('number', $row['cInvCode'])->find();
            $row['shelves_id']      = $inventoryInfo['shelves_id'];
        }
        $warehouseInfo =Db::name('warehouse')->where('number',$row['cWhCode'])->find();
        $row['warehouse_id'] = $warehouseInfo['id'];
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    public function choose(){
        return $this->index();
    }
}
